import NavBar from '@/components/NavBar'
import { Dialog, List, Popup, Toast } from 'antd-mobile'
import styles from './index.module.scss'
import { getUserProfile,editUserPhoto,editUserProfile, clearAuth} from '@/store/action/user'
import { useEffect, useRef, useState } from 'react'
import { useDispatch } from 'react-redux'
import { useAppSelector } from '@/store';
import Input from '@/components/Input'
import Textarea from '@/components/Textarea'
import { DatePicker } from 'antd-mobile/es/components/date-picker/date-picker'
import dayjs from 'dayjs'
import { removeTokenInfo } from '@/utils/storage'
import history from '@/utils/history'
type EditType = 'photo' | 'gender';
type PopupRight = {
  visible: boolean
  type: 'name' | 'intro' | ''
}
export default function ProfileEdit() {
  const dispatch = useDispatch();
  useEffect(() => {
    // 2. useEffect挂载时，发送请求
    dispatch(getUserProfile());
  }, [dispatch]);
    // 日期选择器
  const [pickShow, setPickShow] = useState(false)
  // 点击日期选择器确认按钮时触发
  const handleConfirm = (value: Date) => {
    // 利用 dayjs 格式化日期
    const birthday = dayjs(value).format('YYYY-MM-DD')
    // 更新生日信息
    dispatch(editUserProfile({ birthday }))
    Toast.show('更新成功');
    setPickShow(false)
  }
  const { profile } = useAppSelector((state) => state.user);
  // 底部弹出框状态
  const [popupBottom, setPopupBottom] = useState(false)
  const [editType, setEditType] = useState('' as EditType);
  // 右侧弹出框状态
  const [popupRight, setPopupRight] = useState<PopupRight>({ visible: false, type: '' })
  // 表单：用于绑定授课组件的状态
  const [name, setName] = useState('')
  // 用于绑定个人简介
  const [intro, setIntro] = useState('')
   // 打开右侧弹出层的时候：需要默认显示用户昵称或用户简介
   const popupRightOpen = (type: 'name' | 'intro') => {
    // 设置表单默认值
    if (type === 'name') {
      setName(profile.name)
    }else {
      setIntro(profile.intro ||'')
    }
    // 打开右侧弹出层
    setPopupRight({ visible: true, type: type })
  }
  // 修改名称
  const handleSubmit=()=>{
    if (popupRight.type === 'name') {
      console.log('提交的name值为', name)
      dispatch(editUserProfile({ name }))
      Toast.show('更新成功');
      popupClose()
    }else if(popupRight.type === 'intro'){
      dispatch(editUserProfile({ intro }))
      Toast.show('更新成功');
      popupClose()

    }
  }
   // 按回车键提交
   const handleKeyUp = (e:React.KeyboardEvent<HTMLInputElement>) => {
    // console.log(e.key)
    if (e.key === 'Enter') {
      handleSubmit()
    }
 
  }
  const handleEdit = (type: EditType) => {
    setEditType(type);
    setPopupBottom(true);
  };
  // 1. 创建ref
  const uploadRef = useRef<HTMLInputElement>(null);
  // 修改图片
  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    // 💥 files可能为null，绕开ts提示
    if (e.target.files) {
      console.log('e.target.files[0]  ----->  ', e.target.files[0]);
      const formData = new FormData();
      // 💥 3. 创建formData，添加数据
      formData.append('photo', e.target.files[0]);
      // 发起请求
      dispatch(editUserPhoto(formData));
      setPopupBottom(false);
      Toast.show('更新成功');
    }
  };
  // 修改性别
  const handleEditProfie = (gender: number) => {
    dispatch(editUserProfile({ gender }));
    setPopupBottom(false);
    Toast.show('更新成功');
  };
  const popupClose = () => {
        // 关闭右侧弹出层
        setPopupRight({ visible: false, type: '' })
      }
  const renderModifyNode = (editType: EditType) => {
    switch (editType) {
      case 'photo':
        return (
          <>
            <div className="list-item" onClick={() => uploadRef.current?.click()}>
              拍照
            </div>
            <div className="list-item" onClick={() => uploadRef.current?.click()}>本地选择</div>
            <div onClick={() => setPopupBottom(false)} className="list-item">
              取消
            </div>
          </>
        );

      case 'gender':
        return (
          <>
            <div className="list-item" onClick={()=>handleEditProfie(0)}>男</div>
            <div className="list-item" onClick={()=>handleEditProfie(1)}>女</div>
            <div onClick={() => setPopupBottom(false)} className="list-item">
              取消
            </div>
          </>
        );
      default:
        return null;
    }
  };
  // 退出登录
  const handleLogout = () => {
    Dialog.confirm({
      title: '温馨提示',
      content: '你确定要退出吗',
      onConfirm: () => {
        // 清理本地存储的 Token 信息
        removeTokenInfo()
        // 清理 redux 的 Token 信息
        dispatch(clearAuth())
        // 跳转到登录页
        history.push('/login')
        // 提示
        Toast.show({ content: '退出登录成功' })
      },
    })
  }
  return (
    <div className={styles.root}>
      <div className='content'>
        {/* 顶部导航栏 */}
        <NavBar>个人资料</NavBar>

        <div className='wrapper'>
          {/* 列表一：显示头像、昵称、简介 */}
          <List className='profile-list'>
            <List.Item arrow extra={<img className='avatar' src={profile.photo} alt='' />} onClick={() => handleEdit('photo')}>
              头像
            </List.Item>
{/* 
            <List.Item arrow extra={profile.name}  onClick={() => setPopupRight({ visible: true, type: 'name' })}> */}
            <List.Item onClick={() => popupRightOpen('name')} arrow extra={profile.name}>
              昵称
            </List.Item>

            <List.Item arrow extra={<span className='intro'>{profile.intro || '未填写'}</span>}   onClick={() => popupRightOpen('intro')}>
              简介
            </List.Item>

            <List.Item arrow extra={profile.gender === 0 ? '男' : '女'} onClick={()=>handleEdit('gender')}>
              性别
            </List.Item>
            <List.Item arrow extra={profile.birthday} onClick={() => setPickShow(true)}>
              生日
            </List.Item>
          </List>

          {/* 文件选择框，用于头像图片的上传 */}
          <input onChange={(e) => handleFileChange(e)}
            ref={uploadRef}
            className="avatar-upload"
            type="file"
            accept=".png,.jpg" />
        </div>

        {/* 底部栏：退出登录按钮 */}
        <div className='logout'>
          <button className='btn' onClick={handleLogout}>退出登录</button>
        </div>
      </div>
        {/* 底部弹出层 */}
        <Popup visible={popupBottom} position='bottom' bodyClassName='popup-bottom-list' onMaskClick={() => setPopupBottom(false)}>
          {/* <div className='list-item' onClick={() => uploadRef.current?.click()}>拍照</div>
          <div className='list-item'>本地选择</div>
          <div className='list-item' onClick={() => setPopupBottom(false)} >取消</div> */}
           {renderModifyNode(editType)}
        </Popup>
         {/* 右侧弹出层 */}
       <Popup visible={popupRight.visible} position='right' bodyClassName='popup-right'      // 不可见时卸载内容，用于配合加载表单的时候自动获取焦点
          destroyOnClose>
         <NavBar onBack={() => popupClose()} right={<span className="submit-btn" onClick={handleSubmit} >提交</span>}>编辑用户信息</NavBar>
         <div className='edit-content'>
         {popupRight.type === 'name' ? (
              <>
                <h3 className='edit-title'>编辑昵称</h3>
                {/* <Input className='edit-input' /> */}
                 {/* autoFocus 自动获取焦点 */}
                 {/* // 受控组件 value  onChange 组合 */}
                 <Input className='edit-input' autoFocus  value={name}  onChange={(e) => setName(e.target.value)} onKeyDown={handleKeyUp}/>
              </>
            ) : (
              <>
                <h3 className='edit-title'>编辑简介</h3>
                <Textarea
                  placeholder='请输入个人简介'
                  autoFocus
                  maxLength={10}
                  value={intro}
                  onChange={(e) => setIntro(e.target.value)}
                />
              </>
            )}
         </div>
       </Popup>
       <DatePicker
          visible={pickShow}
          min={new Date('1960-01-01')}
          max={new Date()}
          value={new Date(profile.birthday)}
          onConfirm={handleConfirm}
        />
    </div>
  )
}
